<template>
  <div class="search">
    <add v-if="currView=='add'" @close="currView='index'" @submited="submited"/>
    <edit v-if="currView=='edit'" @close="currView='index'" @submited="submited" :data="formData"/>
    <Card v-show="currView=='index'">
      <Row v-show="openSearch" @keydown.enter.native="handleSearch">
        <Form ref="searchForm" :model="searchForm" inline :label-width="70" class="search-form">
          <FormItem label="奖项编号" prop="awardId">
            <Input type="text" v-model="searchForm.awardId" placeholder="请输入奖项编号" clearable style="width: 200px"/>
          </FormItem>
          <FormItem label="奖项名称" prop="awardName">
            <Input type="text" v-model="searchForm.awardName" placeholder="请输入奖项名称" clearable style="width: 200px"/>
          </FormItem>
          <span v-if="drop">
                    <FormItem label="获奖人" prop="awardee">
                        <Input type="text" v-model="searchForm.awardee" placeholder="请输入获奖人" clearable
                               style="width: 200px"/>
                    </FormItem>
                    <FormItem label="部门" prop="departmentName">
                      <Select v-model="searchForm.departmentName" placeholder="请选择" clearable style="width: 200px">
                         <Option v-for="(item, i) in dictDepartmentName" :key="i" :value="item.value">{{item.title}}</Option>
                       </Select>
                    </FormItem>
                    <FormItem label="颁奖单位" prop="unit">
                        <Input type="text" v-model="searchForm.unit" placeholder="请输入颁奖单位" clearable
                               style="width: 200px"/>
                    </FormItem>
                    <FormItem label="获奖日期" prop="time">
                        <DatePicker type="date" format="yyyy-MM-dd" @on-change="changeTime" placeholder="请选择" clearable
                                    style="width: 200px"></DatePicker>
                    </FormItem>
                </span>
          <FormItem style="margin-left:-35px;" class="br">
            <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
            <Button @click="handleReset">重置</Button>
            <a class="drop-down" @click="dropDown">
              {{ dropDownContent }}
              <Icon :type="dropDownIcon"></Icon>
            </a>
          </FormItem>
        </Form>
      </Row>
      <Row class="operation">
        <Button @click="add" type="primary" icon="md-add">添加</Button>
        <Button @click="delAll" icon="md-trash">批量删除</Button>
        <Button @click="getDataList" icon="md-refresh">刷新</Button>
        <Button ghost icon="ios-print" type="info" @click="printModalVisible=true">打印</Button>
        <Button ghost icon="ios-download" type="success"@click="importModalVisible=true">导入数据</Button>
        <Button @click="exportAll" icon="ios-print" type="warning" ghost>Excel表格</Button>
        <Button type="dashed" @click="openTip=!openTip">{{ openTip ? "关闭提示" : "开启提示" }}</Button>
      </Row>
      <Alert show-icon v-show="openTip">
        已选择
        <span class="select-count">{{ selectList.length }}</span> 项
        <a class="select-clear" @click="clearSelectAll">清空</a>
      </Alert>
      <Table id='printObj' :loading="loading" border :columns="columns" :data="data" ref="table" sortable="custom"
             @on-sort-change="changeSort" @on-selection-change="changeSelect"></Table>
      <Row type="flex" justify="end" class="page">
        <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize" @on-change="changePage"
              @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]" size="small" show-total show-elevator
              show-sizer></Page>
      </Row>
    </Card>

    <!-- 自定义打印数据 -->
    <Modal v-model="printModalVisible" title="确认导出" @on-ok="printJson">
      <Form ref="exportForm" :label-width="100">
        <Alert type="warning" show-icon>表头默认最好不填</Alert>
        <FormItem label="打印表头">
          <Input v-model="filename" placeholder="请输入表头" />
        </FormItem>
        <FormItem label="自定义打印列">
          <CheckboxGroup v-model="chooseColumns">
            <Checkbox
                v-for="(item, i) in exportColumns"
                :key="i"
                :disabled="item.disabled"
                :label="item.title"
                :value="item.checked"
            ></Checkbox>
          </CheckboxGroup>
        </FormItem>
      </Form>
    </Modal>

    <!-- 自定义导出数据 -->
    <Modal
        v-model="exportModalVisible"
        :title="exportTitle"
        :loading="loadingExport"
        @on-ok="exportCustomData"
    >
      <Form ref="exportForm" :label-width="100">
        <FormItem label="导出文件名">
          <Input v-model="filename"/>
        </FormItem>
        <FormItem label="自定义导出列">
          <CheckboxGroup v-model="chooseColumns">
            <Checkbox
                v-for="(item, i) in exportColumns"
                :label="item.title"
                :key="i"
                :value="item.checked"
                :disabled="item.disabled"
            ></Checkbox>
          </CheckboxGroup>
        </FormItem>
      </Form>
    </Modal>

    <Drawer title="导入数据" closable v-model="importModalVisible" width="1000">
      <div style="display:flex;justify-content: space-between;align-items: center;">
        <Upload action :before-upload="beforeUploadImport" accept=".xls, .xlsx">
          <Button
              :loading="reading"
              icon="ios-cloud-upload-outline"
              style="margin-right:10px"
          >上传Excel文件</Button>
          <span v-if="uploadfile.name">当前选择文件：{{ uploadfile.name }}</span>
        </Upload>
        <Button @click="clearImportData" icon="md-trash">清空数据</Button>
      </div>
      <Alert type="warning" show-icon>导入前请下载查看导入模版数据文件，确保数据格式正确，不得修改列英文名称。</Alert>
      <Table
          :columns="importColumns"
          border
          :height="height"
          :data="importTableData"
          ref="importTable"
      ></Table>
      <div class="drawer-footer">
        <Button @click="downloadTemple" type="info" style="position:absolute;left:15px;">下载导入模板</Button>
        <Button @click="importModalVisible=false">关闭</Button>
        <Button
            :loading="importLoading"
            :disabled="importTableData.length<=0"
            @click="importData"
            style="margin-left:60px"
            type="primary"
        >
          确认导入
          <span v-if="importTableData.length>0">{{importTableData.length}} 条数据</span>
        </Button>
      </div>
    </Drawer>
  </div>
</template>

<script>
// 根据你的实际请求api.js位置路径修改
import {
  getAwardManagementList,
  deleteAwardManagement,
  importDataApi
} from "./api.js";
// 根据你的实际添加编辑组件位置路径修改
import add from "./add.vue";
import edit from "./edit.vue";
// 指定导出列数据
import {exportColumn,importTemplate,awardManagementColumn} from "./exportColumn";
import excel from "@/libs/excel";

export default {
  name: "awardManagement",
  components: {
    add,
    edit,
  },
  data() {
    return {
      openSearch: true, // 显示搜索
      openTip: true, // 显示提示
      formData: {},
      currView: "index",
      loading: true, // 表单加载状态
      drop: false,
      dropDownContent: "展开",
      dropDownIcon: "ios-arrow-down",
      searchForm: { // 搜索框初始化对象
        pageNumber: 1, // 当前页数
        pageSize: 10, // 页面大小
        sort: "createTime", // 默认排序字段
        order: "desc", // 默认排序方式
      },
      selectList: [], // 多选数据
      columns: [
        // 表头
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          type: "index",
          width: 60,
          align: "center"
        },
        {
          title: "奖项编号",
          key: "awardId",
          minWidth: 120,
          sortable: false,
        },
        {
          title: "奖项名称",
          key: "awardName",
          minWidth: 120,
          sortable: false,
        },
        {
          title: "获奖人",
          key: "awardee",
          minWidth: 120,
          sortable: false,
        },
        {
          title: "奖项级别",
          key: "type",
          minWidth: 120,
          sortable: false,
        },
        {
          title: "部门",
          key: "departmentName",
          minWidth: 120,
          sortable: false,
        },
        {
          title: "颁奖单位",
          key: "unit",
          minWidth: 120,
          sortable: false,
        },
        {
          title: "获奖日期",
          key: "time",
          minWidth: 120,
          sortable: false,
        },
        {
          title: "操作",
          key: "action",
          align: "center",
          width: 150,
          render: (h, params) => {
            return h("div", [
              h(
                  "a", {
                    on: {
                      click: () => {
                        this.edit(params.row);
                      }
                    }
                  },
                  "编辑"
              ),
              h("Divider", {
                props: {
                  type: "vertical",
                },
              }),
              h(
                  "a", {
                    on: {
                      click: () => {
                        this.remove(params.row);
                      }
                    }
                  },
                  "删除"
              )
            ]);
          }
        }
      ],
      data: [], // 表单数据
      pageNumber: 1, // 当前页数
      pageSize: 10, // 页面大小
      total: 0, // 表单数据总数

      exportModalVisible: false,   //导出数据视图
      exportTitle: "确认导出",
      exportData: [],
      exportType: "",
      exportColumns: exportColumn,

      filename: "",
      loadingExport: true,
      chooseColumns: [],

      printModalVisible:false,
      reading: false, // 读取中
      importModalVisible: false, // 导入显示
      importLoading: false, // 导入加载状态
      importTableData: [],
      importColumns: [],
      uploadfile: {
        name: ""
      },

      dictDepartmentName: this.$store.state.dict.DepartmentName,
    };
  },
  methods: {
    init() {
      this.getDataList();
      // 初始化导出列数据
      let array = [];
      this.exportColumns.forEach(e => {
        // 指定列限制权限
        if (
            !this.getStore("roles").includes("ROLE_ADMIN") &&
            e.key == "mobile"
        ) {
          e.title = "[无权导出] " + e.title;
          e.disabled = true;
        } else {
          e.disabled = false;
        }
        array.push(e.title);
      });
      this.chooseColumns = array;
    },
    changeTime(e) {
      this.searchForm.time = e;
    },
    submited() {
      this.currView = "index";
      this.getDataList();
    },
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getDataList();
      this.clearSelectAll();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.getDataList();
    },
    handleSearch() {
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.getDataList();
    },
    handleReset() {
      this.$refs.searchForm.resetFields();
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      // 重新加载数据
      this.getDataList();
    },
    changeSort(e) {
      this.searchForm.sort = e.key;
      this.searchForm.order = e.order;
      if (e.order === "normal") {
        this.searchForm.order = "";
      }
      this.getDataList();
    },
    dropDown() {
      if (this.drop) {
        this.dropDownContent = "展开";
        this.dropDownIcon = "ios-arrow-down";
      } else {
        this.dropDownContent = "收起";
        this.dropDownIcon = "ios-arrow-up";
      }
      this.drop = !this.drop;
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false);
    },
    changeSelect(e) {
      this.selectList = e;
    },
    getDataList() {
      this.loading = true;
      getAwardManagementList(this.searchForm).then(res => {
        this.loading = false;
        if (res.success) {
          this.data = res.result.records;
          this.total = res.result.total;
          if (this.data.length == 0 && this.searchForm.pageNumber > 1) {
            this.searchForm.pageNumber -= 1;
            this.getDataList();
          }
        }
      });
    },
    add() {
      this.currView = "add";
    },
    edit(v) {
      // 转换null为""
      for (let attr in v) {
        if (v[attr] == null) {
          v[attr] = "";
        }
      }
      let str = JSON.stringify(v);
      let data = JSON.parse(str);
      this.formData = data;
      this.currView = "edit";
    },
    remove(v) {
      this.$Modal.confirm({
        title: "确认删除",
        // 记得确认修改此处
        content: "您确认要删除该条数据?",
        loading: true,
        onOk: () => {
          // 删除
          deleteAwardManagement({
            ids: v.id
          }).then(res => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("操作成功");
              this.clearSelectAll();
              this.getDataList();
            }
          });
        }
      });
    },
    delAll() {
      if (this.selectList.length <= 0) {
        this.$Message.warning("您还未选择要删除的数据");
        return;
      }
      this.$Modal.confirm({
        title: "确认删除",
        content: "您确认要删除所选的 " + this.selectList.length + " 条数据?",
        loading: true,
        onOk: () => {
          let ids = "";
          this.selectList.forEach(function (e) {
            ids += e.id + ",";
          });
          ids = ids.substring(0, ids.length - 1);
          // 批量删除
          deleteAwardManagement({
            ids: ids
          }).then(res => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("操作成功");
              this.clearSelectAll();
              this.getDataList();
            }
          });
        }
      });
    },

    exportAll() {
      this.exportType = "all";
      this.exportModalVisible = !this.exportModalVisible;
      this.exportTitle = "确认导出全部 " + this.total + " 条数据";
      getAwardManagementList().then(res => {
        if (res.success) {
          this.exportData = res.result;
        }
      })
    },

    // 自定义导出数据
    exportCustomData() {
      // 文件名
      if (this.filename == "") {
        this.filename = "导出数据";
      }
      // 判断勾选导出列
      let array = [];
      this.exportColumns.forEach(e => {
        this.chooseColumns.forEach(c => {
          if (e.title == c && !e.disabled) {
            array.push(e);
          }
        });
      });
      this.exportColumns = array;
      this.exportModalVisible = false;
      let title = [];
      let key = [];
      this.exportColumns.forEach(e => {
        title.push(e.title);
        key.push(e.key);
      });
      const params = {
        title: title,
        key: key,
        data: this.data,
        autoWidth: true,
        filename: this.filename
      };
      excel.export_array_to_excel(params);
    },

    printJson() {
      printJS({
        printable: this.data,
        header: this.filename,
        gridStyle: "border:1px solid lightgray;text-aligin:center",
        properties: [
          "awardId",
          "awardName",
          "awardee",
          "type",
          "departmentName",
          "unit",
          "time",
        ],
        type: "json",
      });
    },

    beforeUploadImport(file) {
      this.uploadfile = file;
      const fileExt = file.name
          .split(".")
          .pop()
          .toLocaleLowerCase();
      if (fileExt == "xlsx" || fileExt == "xls") {
        this.readFile(file);
        this.file = file;
      } else {
        this.$Notice.warning({
          title: "文件类型错误",
          desc:
              "所选文件‘ " +
              file.name +
              " ’不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。"
        });
      }
      return false;
    },
    // 读取文件
    readFile(file) {
      this.reading = true;
      const reader = new FileReader();
      reader.readAsArrayBuffer(file);
      reader.onerror = e => {
        this.reading = false;
        this.$Message.error("文件读取出错");
      };
      reader.onload = e => {
        const data = e.target.result;
        const { header, results } = excel.read(data, "array");
        const tableTitle = header.map(item => {
          return { title: item, key: item, minWidth: 100, align: "center" };
        });
        this.importTableData = results;
        this.importColumns = tableTitle;
        this.reading = false;
        this.$Message.success("读取数据成功");
      };
    },
    //清空导入数据
    clearImportData() {
      console.log(this.importTableData);
      this.importTableData = [];
      this.importColumns = [];
      this.uploadfile = {};
    },
    downloadTemple() {
      let title = [];
      let key = [];
      awardManagementColumn.forEach(e => {
        title.push(e.title);
        key.push(e.key);
      });
      const params = {
        title:title,
        key: key,
        data: importTemplate,
        autoWidth: true,
        filename: "导入数据模版"
      };
      excel.export_array_to_excel(params);
    },
    importData() {
      this.importLoading = true;
      // 传入导入数据 后端接收body数组列表批量导入
      console.log(this.importTableData);
      importDataApi(this.importTableData).then(res => {
        this.importLoading = false;
        if (res.success) {
          this.importModalVisible = false;
          this.getDataList();
          this.$Modal.info({
            title: "导入结果",
            content: res.message
          });
        }
      });
    },
  },
  mounted() {
    this.init();
  }
};
</script>

<style lang="less">
// 建议引入通用样式 具体路径自行修改 可删除下面样式代码
// @import "@/styles/table-common.less";
.search {
  .operation {
    margin-bottom: 2vh;
  }

  .select-count {
    font-weight: 600;
    color: #40a9ff;
  }

  .select-clear {
    margin-left: 10px;
  }

  .page {
    margin-top: 2vh;
  }

  .drop-down {
    margin-left: 5px;
  }
}
</style>
